package cn.com.ethos.search.index;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;

import cn.com.ethos.search.DbSetting;


abstract public class DbRowStream implements IDocumentStream {

	/**
	 * the boost value for title
	 */
	public static int TITLE_BOOST_VALUE = 10;
	protected Logger logger = Logger.getLogger(DbRowStream.class);
	
	private DbSetting settings;
	private ResultSet cursor;
	private Connection connection ;
	private boolean isConnected;
	private Statement statement;
	private Document currentDocument;
	
	abstract protected Document getDocument(ResultSet cursor) throws SQLException;
	abstract protected String   getQuerySql();
	
	public DbRowStream(DbSetting settings) {
		this.settings = settings;
	}
	
	public Document next() throws SQLException{
		this.currentDocument = this.getDocument(cursor);
		return this.currentDocument;
	}

	public boolean hasNext() throws SQLException{
		return cursor.next();
	}

	public void close(){
		try {
			if(this.isConnected) {
				this.cursor.close();
				this.statement.close();
				this.connection.close();
			}
		} catch(Exception e) {
			logger.error("an unexpected error occured while close connection :" + e.toString());
		}
	}
	
	public void open() throws SQLException,ClassNotFoundException{
		Class.forName(this.settings.getDbDriver());
		connection    = DriverManager.getConnection(settings.getDbUrl(),settings.getDbUser(),settings.getDbPass());
		statement     = connection.createStatement();
		statement.setFetchSize(100);
		String sql    = this.getQuerySql();
		logger.info("@@{ The SQL statement is : " + sql + " }");
		cursor 		  = statement.executeQuery(sql);
		this.isConnected   = true;
	}
}
